package 压缩流;

import java.io.*;
import java.util.zip.*;

public class ZipMultipleFilesExample {
    public static void main(String[] args) throws IOException {
        String[] filesToZip = {"file1.txt", "file2.txt", "image.jpg"};
        String zipFile = "archive.zip";
        for(String file : filesToZip)
        {
            File f = new File(file);
            if(!f.exists())
                f.createNewFile();
        }

        try (FileOutputStream fos = new FileOutputStream(zipFile);
             ZipOutputStream zos = new ZipOutputStream(fos)) {

            // 设置压缩级别
            zos.setLevel(Deflater.DEFAULT_COMPRESSION);

            for (String file : filesToZip) {
                try (FileInputStream fis = new FileInputStream(file)) {
                    // 为每个文件创建ZIP条目
                    ZipEntry zipEntry = new ZipEntry(file);
                    zos.putNextEntry(zipEntry);

                    // 写入文件内容
                    byte[] buffer = new byte[1024];
                    int length;
                    while ((length = fis.read(buffer)) >= 0) {
                        zos.write(buffer, 0, length);
                    }

                    // 关闭当前条目
                    zos.closeEntry();
                } catch (IOException e) {
                    System.err.println("处理文件时出错: " + file);
                    e.printStackTrace();
                }
            }

            System.out.println("多文件压缩完成: " + zipFile);

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
